package com.github.pires.obd.paizhao.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.github.pires.obd.paizhao.R;
import com.github.pires.obd.paizhao.util.Base64BitmapUtil;
import com.github.pires.obd.paizhao.util.LogUtil;
import com.github.pires.obd.paizhao.util.PhotoBitmapUtils;
import com.github.pires.obd.paizhao.util.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_take_phote;
    private static final int REQUEST_PERMISSIONS = 1;
    private Uri imgUriOri;
    private static final int CAMERA_RESULT_CODE = 1;
    private String imgPathOri;
    /*** 图片名字 */
    private String currentImgUriOri;
    private String mFilePath;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initVew();
    }

    private void initVew() {
        btn_take_phote = findViewById(R.id.btn_take_phote);
        btn_take_phote.setOnClickListener(this);

        iv = findViewById(R.id.iv);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_take_phote:
                takePhote();
                break;
        }
    }

    /**
     * 拍照
     */
    private void takePhote() {
        checkCameraPermission();
    }


    /**
     * 检查是否符合打开相机的权限
     */
    private void checkCameraPermission() {
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            ToastUtil.showShort(this, "请在设置中给予相机权限，否则不可使用照相机");
            ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSIONS);
        } else {
            //注册相机权限
            ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSIONS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSIONS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openSysCamera();
                } else {
                    // 勾选了不再询问
                    /**
                     * 跳转到 APP 详情的权限设置页
                     *
                     * 可根据自己的需求定制对话框，点击某个按钮在执行下面的代码
                     */
                    ToastUtil.showShort(this, "没有权限无法打开相机，请在设置中给予相机权限");
                }
                break;
//            case REQUEST_LAST_PERMISSIONS:
//                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    openSysAlubm();
//                } else {
//                    // 勾选了不再询问
//                    /**
//                     * 跳转到 APP 详情的权限设置页
//                     *
//                     * 可根据自己的需求定制对话框，点击某个按钮在执行下面的代码
//                     */
//                    ToastUtil.showShort(this, "没有权限无法打开相机，请在设置中给予文件读取权限");
//                }
//                break;
        }
    }

    String imgName = System.currentTimeMillis() + "TMJF";
    File file = new File(Environment.getExternalStorageDirectory(), imgName);

    /**
     * 打开系统相机
     */
    private void openSysCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
//                new File(Environment.getExternalStorageDirectory(), imgName)));
        try {
            file = createOriImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (file != null) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                imgUriOri = Uri.fromFile(file);
            } else {
                imgUriOri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
            }
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
            startActivityForResult(cameraIntent, CAMERA_RESULT_CODE);
        }
    }

    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    private File createOriImageFile() throws IOException {
        String imgNameOri = "HomePic_" + new SimpleDateFormat(
                "yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(getExternalFilesDir(
                Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        currentImgUriOri = imgNameOri;
        mFilePath = image.getPath();
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
//            case ALBUM_RESULT_CODE: // 相册选择返回
//                if (data != null) {
//                    //获取选择器返回的数据
//                    ArrayList<String> images = new ArrayList<String>();
//                    images.clear();
//                    images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
//                    try {
//                        if (images != null && images.size() > 0) {
//                            base64Images.clear();
//                            setImage(images);
//
//                        } else {
//                            ToastUtil.showShort(this, "没有选择图片");
//                        }
//                    } catch (Exception e) {
//                        ToastUtil.showShort(this, "图片选择失败!");
//                    }
//
//                } else {
//                    ToastUtil.showShort(this, "图片选择失败");
//                }
//                break;
            case CAMERA_RESULT_CODE: // 拍照
                if (file != null) {
                    LogUtil.i("file大小：" + file.length());
//                    Bitmap bitmap = getBitmapFromUri(getImageContentUri(file));
                    Bitmap bitmap = PhotoBitmapUtils.getBitmapFromFilePath(file.getPath());
                    // 1.获取图片路径
                    String currentPath = file.getPath();
                    LogUtil.i("图片路径：" + currentPath);
                    // 2.图片的选择角度做判断
                    int currentPicAngle = 0;
                    currentPicAngle = PhotoBitmapUtils.readPictureDegree(currentPath);

//                    Glide.with(this).load(file).into(iv);

                    if (currentPicAngle != 0) { // 图片旋转了
                        Bitmap currentBit;
                        currentBit = PhotoBitmapUtils.rotateBitmap(PhotoBitmapUtils.compress(bitmap), currentPicAngle); // 压缩图片
                        if (currentBit != null) {
                            LogUtil.i("旋转了：" + currentBit.getAllocationByteCount());

                            setImage(currentBit); // 设置图片

                        } else {
                            ToastUtil.showShort(this, "拍摄失败");
                        }
                    } else {
                        if (bitmap != null) {
                            LogUtil.i("没有旋转：" + bitmap.getAllocationByteCount());
                            setImage(bitmap); // 设置图片
                        } else {
                            ToastUtil.showShort(this, "拍摄失败");
                        }
                    }
                }
                break;
        }
    }

    public void setImage(Bitmap bitmap) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Bitmap cBitmap = PhotoBitmapUtils.compress(bitmap);
                LogUtil.i("压缩后图片大小：" + file.length());

                String base64 = Base64BitmapUtil.bitmapToBase64(cBitmap);

//                Glide.with(MainActivity.this).load(cBitmap).into(iv);
                LogUtil.i("bitmap:" + base64.length());
                LogUtil.i(base64);
                Glide.with(MainActivity.this).load(cBitmap).into(iv);
            }
        });
    }
}